package com.main.crossdomaineventmanagement.event.core;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

public abstract class CustomTransactionListener<T> implements TransactionListener {
    private final ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new JavaTimeModule());  // 仅注册 JavaTime 模块

    /**
     * 执行本地事务（由子类实现）
     */
    protected abstract boolean executeLocalBusiness(T payload);

    /**
     * 检查本地事务状态（由子类实现）
     */
    protected abstract boolean checkLocalBusiness(String transactionId);

    @Override
    public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            T payload = objectMapper.readValue(msg.getBody(), getPayloadType());
            boolean success = executeLocalBusiness(payload);
            return success ?
                    LocalTransactionState.COMMIT_MESSAGE :
                    LocalTransactionState.ROLLBACK_MESSAGE;
        } catch (Exception e) {
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }
    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt msg) {
        String transactionId = msg.getTransactionId();
        boolean isCommitted = checkLocalBusiness(transactionId);
        return isCommitted ?
                LocalTransactionState.COMMIT_MESSAGE :
                LocalTransactionState.ROLLBACK_MESSAGE;
    }

    /**
     * 获取泛型类型（子类需指定具体类型）
     */
    protected abstract Class<T> getPayloadType();
}